package com.sls.api.game.servlet.enfu;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.sls.api.game.pojo.EnfuServerInfo;
import com.sls.api.game.servlet.SuperServlet;
import com.sls.api.util.IpUtil;
import com.sls.api.util.PropertiesUtil;
import com.sls.api.util.ResponseDataXmlFormat;
import com.sls.api.util.UtilMD5Encryption;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.SocketDTO;

/**
 * 
 * @description 恩付商品新增
 * @author Wangxuegang
 * @date 2013-4-28
 */
public class EnfuGoodsAddServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(EnfuGoodsAddServlet.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException, UnavailableException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"GBK");
		resp.setContentType("text/html;charset=GBK");
		resp.setStatus(HttpServletResponse.SC_OK);
		// 合作平台编号
		String partnerId = "";
		// 商品中心商品编号
		String supProductId = "";
		// Sup供货价格单价
		String unitPrice = "";
		// 商品名称
		String name = "";
		// 商品类型
		String productType = "";
		// 商品面值
		String parvalue = "";
		// 时间戳
		String ts = "";
		// 签名字符串
		String sign = "";
		try {
			partnerId = req.getParameter("partnerId");
			supProductId = req.getParameter("supProductId");
			unitPrice = req.getParameter("unitPrice");
			name = req.getParameter("name");

			productType = req.getParameter("productType");
			parvalue = req.getParameter("parvalue");
			ts = req.getParameter("ts");
			sign = req.getParameter("sign");

			String partnerKey = PropertiesUtil.getValue("enfu.md5.key");
			boolean flag = checkData(partnerId, supProductId, unitPrice, name,
					productType, parvalue, ts, sign, partnerKey, resp);
			if (flag) {
				try {
					Gson gson = CommonUtil.gson();
					SocketDTO socketChangeVo = createMsg(partnerId,
							supProductId, unitPrice, name, productType,
							parvalue, ts, sign, req);
					Head head = socketChangeVo.getHead();
					String resCode = head.getResponseCode();
					String resMsg = head.getResponseMessage();

					String bodyStr = socketChangeVo.getBody();
					String resBodyStr = gson.fromJson(bodyStr, String.class);

					String xmlStr = ResponseDataXmlFormat.assembleXmlString(
							resBodyStr, resCode, resMsg);
					resp.getWriter().write(xmlStr);
					resp.getWriter().flush();
					resp.getWriter().close();
				} catch (Exception e) {
					log.error("出错", e);
					ResponseDataXmlFormat.returnResMsg("201", "其他错误", resp);
				}
			}
		} catch (IllegalArgumentException e) {
			log.error("出错", e);
			ResponseDataXmlFormat.returnResMsg("201", "其他错误", resp);
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	/**
	 * 数据校验
	 * 
	 * @param partnerId
	 * @param supProductId
	 * @param unitPrice
	 * @param name
	 * @param productType
	 * @param parvalue
	 * @param ts
	 * @param sign
	 * @param partnerKey
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	private boolean checkData(String partnerId, String supProductId,
			String unitPrice, String name, String productType, String parvalue,
			String ts, String sign, String partnerKey, HttpServletResponse resp)
			throws IOException {

		boolean flag = false;
		// 合作平台编号
		if ("".equals(partnerId) || partnerId == null) {
			log.info("合作平台编号为空");
			ResponseDataXmlFormat
					.returnResMsg("101", "缺少必需参数[partnerId]", resp);
		}
		// 商品中心商品编号
		else if ("".equals(supProductId) || supProductId == null) {
			log.info("商品中心商品编号为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[supProductId]",
					resp);
		}
		// 恩付供货价格单价
		else if ("".equals(unitPrice) || unitPrice == null) {
			log.info("恩付供货价格单价为空");
			ResponseDataXmlFormat
					.returnResMsg("101", "缺少必需参数[unitPrice]", resp);
		}
		// 商品名称
		else if ("".equals(name) || name == null) {
			log.info("商品名称为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[name]", resp);
		}
		// 商品充值类型
		else if ("".equals(productType) || productType == null) {
			log.info("商品类型为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[productType]",
					resp);
		}
		// 商品面值
		else if ("".equals(parvalue) || parvalue == null) {
			log.info("商品面值为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[parvalue]", resp);
		}

		// 时间戳
		else if ("".equals(ts) || ts == null) {
			log.info("时间戳为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[ts]", resp);
		}
		// 签名字符串
		else if ("".equals(sign) || sign == null) {
			log.info("签名字符串为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[sign]", resp);
		} else { // MD5校验
			StringBuilder strbu = new StringBuilder();
			strbu.append("name");
			strbu.append(name.trim());
			strbu.append("partnerId");
			strbu.append(partnerId.trim());
			strbu.append("parvalue");
			strbu.append(parvalue.trim());
			strbu.append("productType");
			strbu.append(productType.trim());
			strbu.append("supProductId");
			strbu.append(supProductId.trim());
			strbu.append("ts");
			strbu.append(ts.trim());
			strbu.append("unitPrice");
			strbu.append(unitPrice.trim());
			strbu.append(partnerKey.trim());
			String data = strbu.toString().trim();

			boolean checkRes = UtilMD5Encryption.checkMD5Signature(data, sign);
			if (checkRes) {
				flag = true;
			} else {
				log.info("MD5数字签名未通过");
				flag = false;
				ResponseDataXmlFormat.returnResMsg("102", "签名失败", resp);
			}
		}
		return flag;
	}

	/**
	 * 创建Json格式socket消息包
	 * 
	 * @param partnerId
	 * @param supProductId
	 * @param unitPrice
	 * @param name
	 * @param productType
	 * @param parvalue
	 * @param ts
	 * @param sign
	 * @return
	 */
	private SocketDTO createMsg(String partnerId, String supProductId,
			String unitPrice, String name, String productType, String parvalue,
			String ts, String sign, HttpServletRequest req) {
		EnfuServerInfo goodsInfo = new EnfuServerInfo();
//		goodsInfo.setPartnerId(partnerId);
//		goodsInfo.setSupProductId(supProductId);
//		goodsInfo.setUnitPrice(unitPrice);
//		goodsInfo.setName(name);
//		goodsInfo.setProductType(productType);
//		goodsInfo.setParvalue(parvalue);
//		goodsInfo.setTs(ts);
//		goodsInfo.setSign(sign);

		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode("");// ======================????????????????????待完善
		head.setIp(IpUtil.getIpAddr(req)); // ---------坚果网络IP
		head.setUserId("0"); // ---------坚果网络用户ID

		return super.send(head, goodsInfo);
	}

}
